
<template>
  <div class="form-builder">
    <PageHeader title="添加表单" />
    
    <div class="builder-container">
      <!-- 表单基本信息 -->
      <a-card title="表单基本信息" class="form-info">
        <a-form layout="vertical">
          <a-form-item label="表单标题">
            <a-input v-model:value="formData.title" placeholder="请输入表单标题" />
          </a-form-item>
          <a-form-item label="表单描述">
            <a-textarea v-model:value="formData.description" placeholder="请输入表单描述" />
          </a-form-item>
          <a-form-item label="表单内容">
            <a-textarea v-model:value="formData.content" placeholder="请输入表单内容" />
          </a-form-item>
        </a-form>
      </a-card>
      
      <div class="builder-content">
        <!-- 左侧字段配置 -->
        <div class="field-config">
          <a-card title="添加表单字段" class="add-field-card">
            <a-form layout="vertical">
              <a-form-item label="字段类型">
                <a-select v-model:value="newField.type" @change="handleTypeChange">
                  <a-select-option value="input">单行文本</a-select-option>
                  <a-select-option value="textarea">多行文本</a-select-option>
                  <a-select-option value="radio">单选</a-select-option>
                  <a-select-option value="checkbox">多选</a-select-option>
                  <a-select-option value="tel">电话</a-select-option>
                  <a-select-option value="email">邮箱</a-select-option>
                  <a-select-option value="country">国家</a-select-option>
                  <a-select-option value="state">省份</a-select-option>
                  <a-select-option value="captcha">验证码</a-select-option>
                  <a-select-option value="question">问题</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="字段标签">
                <a-input v-model:value="newField.label" placeholder="字段显示名称" />
              </a-form-item>
              
              <a-form-item label="占位文本">
                <a-input v-model:value="newField.placeholder" placeholder="输入提示文本" />
              </a-form-item>
              
              <a-form-item label="字段名称">
                <a-input v-model:value="newField.name" placeholder="用于数据提交的字段名" />
              </a-form-item>
              
              <a-form-item label="宽度占比">
                <a-radio-group v-model:value="newField.width">
                  <a-radio-button :value="100">100%</a-radio-button>
                  <a-radio-button :value="50">50%</a-radio-button>
                  <a-radio-button :value="33">33%</a-radio-button>
                </a-radio-group>
              </a-form-item>
              
              <!-- 问题类型额外配置 -->
              <template v-if="newField.type === 'question'">
                <a-form-item label="问题内容">
                  <a-input v-model:value="newField.question" placeholder="输入问题内容" />
                </a-form-item>
                <a-form-item label="答案类型">
                  <a-select v-model:value="newField.answerType">
                    <a-select-option value="radio">单选</a-select-option>
                    <a-select-option value="checkbox">多选</a-select-option>
                    <a-select-option value="textarea">文本回答</a-select-option>
                  </a-select>
                </a-form-item>
              </template>
              
              <!-- 选项类型额外配置 -->
              <template v-if="['radio', 'checkbox', 'question'].includes(newField.type) && newField.answerType !== 'textarea'">
                <a-form-item label="选项配置">
                  <div class="options-config">
                    <div v-for="(option, index) in newField.options" :key="index" class="option-item">
                      <a-input v-model:value="option.label" placeholder="选项文本" />
                      <a-input v-model:value="option.value" placeholder="选项值" />
                      <MinusCircleOutlined @click="removeOption(index)" />
                    </div>
                    <a-button type="dashed" @click="addOption">
                      <PlusOutlined /> 添加选项
                    </a-button>
                  </div>
                </a-form-item>
              </template>
              
              <a-form-item>
                <a-button type="primary" @click="addField" block>添加字段</a-button>
              </a-form-item>
            </a-form>
          </a-card>
          
          <!-- 字段列表 -->
          <a-card title="字段列表" class="fields-list">
            <draggable 
              v-model="formData.fields" 
              item-key="id"
              handle=".drag-handle"
              @end="onDragEnd"
            >
              <template #item="{ element, index }">
                <div class="field-item">
                  <div class="field-header">
                  <Icon icon="ant-design:menu-outlined" />

                    <span>{{ element.label }} ({{ getTypeName(element.type) }})</span>
                    <div class="actions">
                    <Icon icon="ant-design:edit-outlined" @click="editField(index)"/>
                    <Icon icon="ant-design:delete-outlined" @click="removeField(index)" />
x
                  
                    </div>
                  </div>
                </div>
              </template>
            </draggable>
          </a-card>
        </div>
        
        <!-- 右侧表单预览 -->
        <div class="form-preview">
          <a-card title="表单预览">
            <a-form layout="vertical" :model="previewForm" class="preview-form">
              <a-row :gutter="16">
                <template v-for="(field, index) in formData.fields" :key="field.id">
                  <a-col :span="field.width === 100 ? 24 : field.width === 50 ? 12 : 8">
                    <a-form-item :label="field.label">
                      <!-- 根据类型渲染不同表单控件 -->
                      <template v-if="field.type === 'input'">
                        <a-input 
                          v-model:value="previewForm[field.name]" 
                          :placeholder="field.placeholder" 
                        />
                      </template>
                      
                      <template v-else-if="field.type === 'textarea'">
                        <a-textarea 
                          v-model:value="previewForm[field.name]" 
                          :placeholder="field.placeholder" 
                        />
                      </template>
                      
                      <template v-else-if="field.type === 'radio'">
                        <a-radio-group v-model:value="previewForm[field.name]">
                          <a-radio 
                            v-for="option in field.options" 
                            :key="option.value" 
                            :value="option.value"
                          >
                            {{ option.label }}
                          </a-radio>
                        </a-radio-group>
                      </template>
                      
                      <template v-else-if="field.type === 'checkbox'">
                        <a-checkbox-group v-model:value="previewForm[field.name]">
                          <a-checkbox 
                            v-for="option in field.options" 
                            :key="option.value" 
                            :value="option.value"
                          >
                            {{ option.label }}
                          </a-checkbox>
                        </a-checkbox-group>
                      </template>
                      
                      <template v-else-if="field.type === 'tel'">
                        <a-input 
                          v-model:value="previewForm[field.name]" 
                          :placeholder="field.placeholder" 
                          type="tel"
                        />
                      </template>
                      
                      <template v-else-if="field.type === 'email'">
                        <a-input 
                          v-model:value="previewForm[field.name]" 
                          :placeholder="field.placeholder" 
                          type="email"
                        />
                      </template>
                      
                      <template v-else-if="field.type === 'country'">
                        <a-select 
                          v-model:value="previewForm[field.name]" 
                          :placeholder="field.placeholder"
                        >
                          <a-select-option value="china">中国</a-select-option>
                          <a-select-option value="usa">美国</a-select-option>
                          <a-select-option value="uk">英国</a-select-option>
                          <!-- 更多国家... -->
                        </a-select>
                      </template>
                      
                      <template v-else-if="field.type === 'state'">
                        <a-select 
                          v-model:value="previewForm[field.name]" 
                          :placeholder="field.placeholder"
                        >
                          <a-select-option value="beijing">北京</a-select-option>
                          <a-select-option value="shanghai">上海</a-select-option>
                          <a-select-option value="guangdong">广东</a-select-option>
                          <!-- 更多省份... -->
                        </a-select>
                      </template>
                      
                      <template v-else-if="field.type === 'captcha'">
                        <div class="captcha-input">
                          <a-input 
                            v-model:value="previewForm[field.name]" 
                            :placeholder="field.placeholder" 
                            style="width: 60%"
                          />
                          <a-button style="width: 38%; margin-left: 2%">获取验证码</a-button>
                        </div>
                      </template>
                      
                      <template v-else-if="field.type === 'question'">
                        <div class="question-field">
                          <p>{{ field.question }}</p>
                          <template v-if="field.answerType === 'radio'">
                            <a-radio-group v-model:value="previewForm[field.name]">
                              <a-radio 
                                v-for="option in field.options" 
                                :key="option.value" 
                                :value="option.value"
                              >
                                {{ option.label }}
                              </a-radio>
                            </a-radio-group>
                          </template>
                          
                          <template v-else-if="field.answerType === 'checkbox'">
                            <a-checkbox-group v-model:value="previewForm[field.name]">
                              <a-checkbox 
                                v-for="option in field.options" 
                                :key="option.value" 
                                :value="option.value"
                              >
                                {{ option.label }}
                              </a-checkbox>
                            </a-checkbox-group>
                          </template>
                          
                          <template v-else>
                            <a-textarea 
                              v-model:value="previewForm[field.name]" 
                              :placeholder="field.placeholder" 
                            />
                          </template>
                        </div>
                      </template>
                    </a-form-item>
                  </a-col>
                </template>
              </a-row>
            </a-form>
          </a-card>
          
          <div class="actions">
            <a-button type="primary" @click="submitForm">保存表单</a-button>
            <a-button style="margin-left: 10px">取消</a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { 
  PageHeader,
  Card,
  Form,
  Input,
  Select,
  Radio,
  Checkbox,
  Button,
  message
} from 'ant-design-vue';
import draggable from 'vuedraggable';
import Icon from '#/components/Icons';


interface FormField {
  id: string;
  type: string;
  label: string;
  name: string;
  placeholder: string;
  width: number;
  question?: string;
  answerType?: string;
  options?: Array<{ label: string; value: string }>;
}

export default defineComponent({
  name: 'FormBuilder',
  components: {
    PageHeader,
    ACard: Card,
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    ATextarea: Input.TextArea,
    ASelect: Select,
    ASelectOption: Select.Option,
    ARadio: Radio,
    ARadioGroup: Radio.Group,
    ARadioButton: Radio.Button,
    ACheckbox: Checkbox,
    ACheckboxGroup: Checkbox.Group,
    AButton: Button,
    MenuOutlined,
    EditOutlined,
    DeleteOutlined,
    PlusOutlined,
    MinusCircleOutlined,
    draggable
  },
  setup() {
    // 表单数据
    const formData = reactive({
      title: '',
      description: '',
      content: '',
      fields: [] as FormField[]
    });
    
    // 预览表单数据
    const previewForm = reactive({});
    
    // 新字段配置
    const newField = reactive({
      type: 'input',
      label: '',
      name: '',
      placeholder: '',
      width: 100,
      question: '',
      answerType: 'radio',
      options: [] as Array<{ label: string; value: string }>
    });
    
    // 当前编辑的字段索引
    const editingIndex = ref<number | null>(null);
    
    // 添加选项
    const addOption = () => {
      newField.options.push({ label: '', value: '' });
    };
    
    // 移除选项
    const removeOption = (index: number) => {
      newField.options.splice(index, 1);
    };
    
    // 处理类型变化
    const handleTypeChange = (type: string) => {
      if (['radio', 'checkbox', 'question'].includes(type)) {
        if (!newField.options || newField.options.length === 0) {
          newField.options = [{ label: '', value: '' }];
        }
      } else {
        newField.options = [];
      }
      
      // 设置默认名称
      if (!newField.name) {
        newField.name = type + '_' + Date.now().toString().slice(-4);
      }
    };
    
    // 添加字段
    const addField = () => {
      if (!newField.label || !newField.name) {
        message.warning('请填写字段标签和名称');
        return;
      }
      
      if (newField.type === 'question' && !newField.question) {
        message.warning('请填写问题内容');
        return;
      }
      
      if (['radio', 'checkbox', 'question'].includes(newField.type) && 
          newField.answerType !== 'textarea' &&
          (!newField.options || newField.options.some(opt => !opt.label || !opt.value))) {
        message.warning('请填写完整的选项');
        return;
      }
      
      const field: FormField = {
        id: 'field_' + Date.now(),
        type: newField.type,
        label: newField.label,
        name: newField.name,
        placeholder: newField.placeholder,
        width: newField.width
      };
      
      if (newField.type === 'question') {
        field.question = newField.question;
        field.answerType = newField.answerType;
      }
      
      if (['radio', 'checkbox', 'question'].includes(newField.type) && 
          newField.answerType !== 'textarea') {
        field.options = [...newField.options];
      }
      
      if (editingIndex.value !== null) {
        // 更新现有字段
        formData.fields[editingIndex.value] = field;
        editingIndex.value = null;
      } else {
        // 添加新字段
        formData.fields.push(field);
      }
      
      // 重置新字段配置
      resetNewField();
      
      // 初始化预览表单数据
      initPreviewForm();
    };
    
    // 编辑字段
    const editField = (index: number) => {
      const field = formData.fields[index];
      Object.assign(newField, {
        type: field.type,
        label: field.label,
        name: field.name,
        placeholder: field.placeholder || '',
        width: field.width,
        question: field.question || '',
        answerType: field.answerType || 'radio',
        options: field.options ? [...field.options] : []
      });
      
      editingIndex.value = index;
    };
    
    // 移除字段
    const removeField = (index: number) => {
      formData.fields.splice(index, 1);
      initPreviewForm();
    };
    
    // 重置新字段配置
    const resetNewField = () => {
      Object.assign(newField, {
        type: 'input',
        label: '',
        name: '',
        placeholder: '',
        width: 100,
        question: '',
        answerType: 'radio',
        options: []
      });
    };
    
    // 初始化预览表单数据
    const initPreviewForm = () => {
      formData.fields.forEach(field => {
        if (field.type === 'checkbox') {
          previewForm[field.name] = [];
        } else {
          previewForm[field.name] = '';
        }
      });
    };
    
    // 获取类型名称
    const getTypeName = (type: string) => {
      const typeMap: Record<string, string> = {
        input: '单行文本',
        textarea: '多行文本',
        radio: '单选',
        checkbox: '多选',
        tel: '电话',
        email: '邮箱',
        country: '国家',
        state: '省份',
        captcha: '验证码',
        question: '问题'
      };
      return typeMap[type] || type;
    };
    
    // 拖拽结束
    const onDragEnd = () => {
      // 可以在这里添加排序后的处理逻辑
    };
    
    // 提交表单
    const submitForm = () => {
      if (!formData.title) {
        message.warning('请填写表单标题');
        return;
      }
      
      if (formData.fields.length === 0) {
        message.warning('请添加至少一个表单字段');
        return;
      }
      
      // 这里调用API保存表单
      console.log('表单数据:', formData);
      message.success('表单保存成功');
    };
    
    return {
      formData,
      previewForm,
      newField,
      addOption,
      removeOption,
      handleTypeChange,
      addField,
      editField,
      removeField,
      getTypeName,
      onDragEnd,
      submitForm
    };
  }
});
</script>

<style lang="scss" scoped>
.form-builder {
  height: 100%;
  
  .builder-container {
    padding: 20px;
    
    .form-info {
      margin-bottom: 20px;
    }
    
    .builder-content {
      display: flex;
      gap: 16px;
      
      .field-config {
        width: 400px;
        
        .add-field-card, .fields-list {
          margin-bottom: 16px;
        }
        
        .options-config {
          .option-item {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
            
            .anticon {
              color: #ff4d4f;
              cursor: pointer;
              margin-top: 8px;
            }
          }
        }
        
        .field-item {
          padding: 8px;
          margin-bottom: 8px;
          border: 1px solid #f0f0f0;
          border-radius: 4px;
          
          .field-header {
            display: flex;
            align-items: center;
            
            .anticon {
              margin-right: 8px;
              cursor: move;
            }
            
            .actions {
              margin-left: auto;
              
              .anticon {
                margin-left: 8px;
                color: #666;
                
                &:hover {
                  color: #1890ff;
                }
              }
            }
          }
        }
      }
      
      .form-preview {
        flex: 1;
        
        .preview-form {
          .captcha-input {
            display: flex;
          }
          
          .question-field {
            p {
              font-weight: bold;
              margin-bottom: 8px;
            }
          }
        }
        
        .actions {
          margin-top: 16px;
          text-align: right;
        }
      }
    }
  }
}
</style>